/**
 * @author ashok
 * Chatter Notifier App.
 * 
 * Description: trigger for ovide creating duplicate profile for a user.
 * 
 * Copyright:  Copyright 2010
 * 
 * This file is part of Chatter Notifier. 
 * 
 * Chatter Notifier is free software: you can redistribute it and/or modify
 * it under the terms of the New BSD license.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
trigger duplicateChatterProfileCheck on Chatter_Profile__c (before insert) {
    
    List<String> userIdList = new List<String>();
    
    for(Integer i=0; i< Trigger.size; i++) {
        Chatter_Profile__c cp = Trigger.new[i];
        if(cp.User__c != null) {
        	userIdList.add(cp.User__c);
        }
    }
    
    Map<String, Chatter_Profile__c> cpDuplicateMap = new Map<String, Chatter_Profile__c>();
        
    List<Chatter_Profile__c> cpList = [select id, user__c from Chatter_Profile__c where user__c in : userIdList];
    
    if(cpList != null && !cpList.isEmpty()) {
    	for(Chatter_Profile__c cp : cpList) {
    		cpDuplicateMap.put(''+cp.user__c, cp);
    	}
    } 
    
    Map<String, Chatter_Profile__c> cpInMemoryMap = new Map<String, Chatter_Profile__c>();
    
    for(Integer i=0; i< Trigger.size; i++) {
    	Chatter_Profile__c cpNew = Trigger.new[i];
    	if(cpDuplicateMap.containsKey(cpNew.user__c) || cpInMemoryMap.containsKey(cpNew.user__c)) {
    		cpNew.addError('Not able to create a duplicate profile for selected user. ');
    	}
    	cpInMemoryMap.put(''+cpNew.user__c, cpNew);
    }
}